package com.xlongwei.todays.config;

import java.util.List;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.sql.SqlQuerier;
import org.noear.solon.data.sql.SqlSpec;
import org.noear.solon.data.sql.SqlUtils;
import org.noear.solon.data.sql.bound.RowConverter;
import lombok.extern.slf4j.Slf4j;

/**
 * 包装SQLException为RuntimeException
 */
@Slf4j
@Component
public class MySqlUtils {
    @Inject
    SqlUtils sqlUtils;

    public MySqlExecutor sql(SqlSpec sqlSpec) {
        return sql(sqlSpec.getSql(), sqlSpec.getArgs());
    }

    public MySqlExecutor sql(String sql, Object... args) {
        if (log.isDebugEnabled()) {
            log.debug(sql.replace("?", "'{}'"), args);
        }
        return new MySqlExecutor(sqlUtils.sql(sql, args));
    }

    /**
     * 需要SqlExecutor其他方法继续复制即可
     */
    public static class MySqlExecutor {
        private SqlQuerier sqlExecutor;

        public MySqlExecutor(SqlQuerier sqlExecutor) {
            this.sqlExecutor = sqlExecutor;
        }

        public <T> T queryValue() {
            try {
                return sqlExecutor.queryValue();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public <T> T queryRow(Class<T> tClass) {
            try {
                return sqlExecutor.queryRow(tClass);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public <T> List<T> queryRowList(Class<T> tClass) {
            try {
                return sqlExecutor.queryRowList(tClass);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public <T> List<T> queryRowList(RowConverter<T> converter) {
            try {
                return sqlExecutor.queryRowList(converter);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public int update() {
            try {
                return sqlExecutor.update();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public <T> T updateReturnKey() {
            try {
                return sqlExecutor.updateReturnKey();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
